package com.xyz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.xyz.dto.BusinessAnnounceDto;
import com.xyz.dto.enums.EnumAnnBusinessType;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.AnnounceService;
import com.xyz.service.CommonService;
import com.xyz.service.PartService;
import com.xyz.service.RepairService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.LoginInfo;
import com.xyz.dto.enums.EnumRepState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class AnnounceServiceImpl implements AnnounceService {

    @Autowired
    private PartService partService;

    @Autowired
    private BusinessAnnounceMapper businessAnnounceMapper;

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Autowired
    private RepairWorkOrderFlowMapper repairWorkOrderFlowMapper;

    @Autowired
    private UpkeepWorkOrderMapper upkeepWorkOrderMapper;

    @Autowired
    private UpkeepWorkOrderFlowMapper upkeepWorkOrderFlowMapper;

    @Autowired
    private UpkeepPartMapper upkeepPartMapper;

    @Autowired
    private RepairService repairService;

    @Autowired
    private RepairMaintenanceMapper repairMaintenanceMapper;

    @Autowired
    private CommonService commonService;
    /*
     * 维修单审核
     * */
    @Override
    public DataResult insertAnnounce(LoginInfo loginInfo, BusinessAnnounceDto businessAnnounceDto) throws Exception {
        int annState = Integer.parseInt(businessAnnounceDto.getAnnState());
        long sourceId = Long.parseLong(businessAnnounceDto.getSourceId());
        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(sourceId);
        if (getRepairWorkOrder == null) {
            return DataResult.build9250("获取工单信息失败！");
        }

        if (!getRepairWorkOrder.getRepState().equals(EnumRepState.PENDING_ANNOUNCE.getRepState())) {
            return DataResult.build9250("待审核状态工单才能审核！");
        }


        RepairWorkOrder repairWorkOrder = new RepairWorkOrder();
        repairWorkOrder.setRepId(sourceId);
        repairWorkOrder.setRepTime(new Date());
        repairWorkOrder.setAnnounceEmployeeId(loginInfo.getLoginEmployeeId());
        repairWorkOrder.setEstimatedWorkHour(Integer.parseInt(businessAnnounceDto.getEstimatedWorkHour()));
        RepairWorkOrderFlow workOrderFlow = new RepairWorkOrderFlow();
        //1审核通过；2审核驳回
        if (annState == 1) {
            repairWorkOrder.setRepState(EnumRepState.PENDING_RECEIVE.getRepState());
            workOrderFlow.setState(EnumRepState.PENDING_RECEIVE.getRepState());
            workOrderFlow.setFlowDesc("审核通过");

        } else {
            repairWorkOrder.setRepState(EnumRepState.MAINTENANCE_NO.getRepState());
            workOrderFlow.setState(EnumRepState.MAINTENANCE_NO.getRepState());
            workOrderFlow.setFlowDesc("审核驳回");
        }

        //保存审核记录
        BusinessAnnounce businessAnnounce = new BusinessAnnounce();
        businessAnnounce.setSourceId(sourceId);
        businessAnnounce.setBusType(EnumAnnBusinessType.REPAIR.getBusType());
        businessAnnounce.setAnnState(annState);
        businessAnnounce.setEmployeeId(loginInfo.getLoginEmployeeId());
        if (StrUtil.isNotBlank(businessAnnounceDto.getAnnExplain())) {
            businessAnnounce.setAnnExplain(businessAnnounceDto.getAnnExplain());
        } else {
            businessAnnounce.setAnnExplain("");
        }
        businessAnnounce.setAnnTime(new Date());
        businessAnnounce.setCreateTime(new Date());


        workOrderFlow.setRepId(sourceId);
        workOrderFlow.setEmployeeId(loginInfo.getLoginEmployeeId());

        workOrderFlow.setFlowType(2);
        workOrderFlow.setDisEmployeeId(0L);
        workOrderFlow.setCreateTime(new Date());

        // 审核通过
        if(annState == 1){
            Long employeeId = repairService.findWorker();
            if(employeeId != null && employeeId > 0){
                // 指定维修人

                //修改维修单状态
                RepairMaintenance repairMaintenance = new RepairMaintenance();
                repairMaintenance.setRepId(sourceId);
                repairMaintenance.setDisTime(new Date());
                repairMaintenance.setMtcState(EnumRepState.ALLOCATED.getRepState());
                repairMaintenance.setCreateTime(new Date());
                repairMaintenance.setDisType(3);
                repairMaintenance.setDisEmployeeId(loginInfo.getLoginEmployeeId());
                repairMaintenance.setEmployeeId(employeeId);


                //修改工单状态
                repairWorkOrder.setMaintenEmployeeId(repairMaintenance.getEmployeeId());
                repairWorkOrder.setRepState(EnumRepState.ALLOCATED.getRepState());
                repairWorkOrderMapper.updateByPrimaryKeySelective(repairWorkOrder);

                businessAnnounceMapper.insertSelective(businessAnnounce);
                repairMaintenanceMapper.insertSelective(repairMaintenance);

                RepairWorkOrderFlow workOrderFlow1 = new RepairWorkOrderFlow();
                workOrderFlow1.setRepId(repairWorkOrder.getRepId());
                workOrderFlow1.setEmployeeId(repairMaintenance.getEmployeeId());
                workOrderFlow1.setSourceId(repairMaintenance.getId());
                workOrderFlow1.setDisEmployeeId(loginInfo.getLoginEmployeeId());
                workOrderFlow1.setFlowDesc("系统自动指派工单");
                workOrderFlow1.setFlowType(3);
                workOrderFlow1.setState(EnumRepState.ALLOCATED.getRepState());
                workOrderFlow1.setCreateTime(new Date());

                workOrderFlow.setSourceId(businessAnnounce.getId());
                repairWorkOrderFlowMapper.insert(workOrderFlow);
                repairWorkOrderFlowMapper.insert(workOrderFlow1);

                //待办
                commonService.insertMessageBacklog(
                        repairMaintenance.getEmployeeId(),
                        "【"+getRepairWorkOrder.getWorkOrderCode()+"】维修单已分配到您，请处理",
                        "【" + getRepairWorkOrder.getWorkOrderCode() + "】已分配到您，维修设备：【" + getRepairWorkOrder.getEmCode() + "】-【" + getRepairWorkOrder.getEmName() + "】，地点在【" + getRepairWorkOrder.getEmLocation()  + "】，工单在【30分钟】后自动进入处理中，请尽快到场处理。",
                        2, 2, repairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
                );
                return DataResult.build9100();
            }
        }
        //修改维修工单状态
        repairWorkOrderMapper.updateByPrimaryKeySelective(repairWorkOrder);

        int i = businessAnnounceMapper.insertSelective(businessAnnounce);
        if (i == 0) {
            return DataResult.build9250("审核记录创建失败!!");
        }
        workOrderFlow.setSourceId(businessAnnounce.getId());
        repairWorkOrderFlowMapper.insert(workOrderFlow);
        return DataResult.build9100();
    }

    /*
     * 维保单审核
     * */
    @Override
    public DataResult insertAnnounceByUpkeep(LoginInfo loginInfo, BusinessAnnounceDto businessAnnounceDto) throws Exception {
        int annState = Integer.parseInt(businessAnnounceDto.getAnnState());
        long sourceId = Long.parseLong(businessAnnounceDto.getSourceId());
        UpkeepWorkOrder getUpkeepWorkOrder = upkeepWorkOrderMapper.selectByPrimaryKey(sourceId);
        if (getUpkeepWorkOrder == null) {
            return DataResult.build9250("获取工单信息失败！");
        }

        if (!getUpkeepWorkOrder.getUpkeepState().equals(EnumRepState.PENDING_ANNOUNCE.getRepState())) {
            return DataResult.build9250("待审核状态工单才能审核！");
        }
        UpkeepWorkOrder upkeepWorkOrder = new UpkeepWorkOrder();
        UpkeepPartExample keepPartexample = new UpkeepPartExample();
        keepPartexample.createCriteria().andUpkeepIdEqualTo(getUpkeepWorkOrder.getUpkeepId());
        List<UpkeepPart> upkeepParts = upkeepPartMapper.selectByExample(keepPartexample);
        if (CollUtil.isNotEmpty(upkeepParts)) {
            Map<Long, Integer> partMap = new HashMap<>();
            for (UpkeepPart upkeepPart : upkeepParts) {
                partMap.put(upkeepPart.getPartId(), upkeepPart.getPartNum());
            }
            long orderId = partService.insertOrderOut(loginInfo, getUpkeepWorkOrder.getUpkeepId(), getUpkeepWorkOrder.getWorkOrderCode(), partMap);
            if (orderId == 0) {
                return DataResult.build9250("零件库存不足！");
            }
            upkeepWorkOrder.setOrderId(orderId);
        }
        upkeepWorkOrder.setUpkeepId(sourceId);
        upkeepWorkOrder.setAnnounceEmployeeId(loginInfo.getLoginEmployeeId());
        upkeepWorkOrder.setEstimatedWorkHour(Integer.parseInt(businessAnnounceDto.getEstimatedWorkHour()));
        UpkeepWorkOrderFlow workOrderFlow = new UpkeepWorkOrderFlow();
        //1审核通过；2审核驳回
        if (annState == 1) {
            upkeepWorkOrder.setUpkeepState(EnumRepState.PENDING_RECEIVE.getRepState());
            workOrderFlow.setState(EnumRepState.PENDING_RECEIVE.getRepState());
            workOrderFlow.setFlowDesc("审核通过");
        } else {
            upkeepWorkOrder.setUpkeepState(EnumRepState.INVALID.getRepState());
            workOrderFlow.setState(EnumRepState.INVALID.getRepState());
            workOrderFlow.setFlowDesc("审核驳回");
        }
        //修改维修工单状态
        upkeepWorkOrderMapper.updateByPrimaryKeySelective(upkeepWorkOrder);
        //保存审核记录
        BusinessAnnounce businessAnnounce = new BusinessAnnounce();
        businessAnnounce.setSourceId(sourceId);
        businessAnnounce.setBusType(EnumAnnBusinessType.UPKEEP.getBusType());
        businessAnnounce.setAnnState(annState);
        businessAnnounce.setEmployeeId(loginInfo.getLoginEmployeeId());
        if (StrUtil.isNotBlank(businessAnnounceDto.getAnnExplain())) {
            businessAnnounce.setAnnExplain(businessAnnounceDto.getAnnExplain());
        } else {
            businessAnnounce.setAnnExplain("");
        }
        businessAnnounce.setAnnTime(new Date());
        businessAnnounce.setCreateTime(new Date());
        int i = businessAnnounceMapper.insertSelective(businessAnnounce);
        if (i == 0) {
            return DataResult.build9250("审核记录创建失败!!");
        }

        workOrderFlow.setUpkeepId(sourceId);
        workOrderFlow.setEmployeeId(loginInfo.getLoginEmployeeId());
        workOrderFlow.setSourceId(businessAnnounce.getId());
        workOrderFlow.setFlowType(2);
        workOrderFlow.setDisEmployeeId(0L);
        workOrderFlow.setCreateTime(new Date());
        upkeepWorkOrderFlowMapper.insert(workOrderFlow);
        return DataResult.build9100();
    }
}
